/* 
 * Modbus app for RTU.
 * Copyright (c) 2012  apleilx
 * All rights reserved.
 * no limite
 */

/* ----------------------- Platform includes --------------------------------*/
#define _MAPP_MODULE_
#include "mbapp.h"
#include "os_obj.h"                                          // RTOS object definitions
#include "pincfg.h"
#include "sys_task.h"
#include "bsp_hal.h"
#include "common.h"

#define TEST_MODE       MB_RTU_SLAVE

mb_baud_tab_create;
    
uint8_t mbTestErrCnt = 0;
uint8_t mbTestOkCnt = 0;

typedef struct
{
    uint16_t reg_r[64];
    uint16_t reg_w[64];
    uint16_t pv_r[64];
    uint16_t pv_w[64];
} mb_tst_type;

mb_tst_type mb_tst;

void rcv_end_handle_comp(uint8_t ErrSt);

/*****************************************************************************//*!
* @brief   	Slave device handle.
*               
* @param   none
*
* @return  none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/   
void modbus_task (void * thread_input)
{
    UINT os_err, ticks;
    ULONG event;
    
    mb_obj_init(&mb.obj03);

    //slave config
    mb03_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_115200], MB_PAR_NONE);
    mb.obj03.slave_id = 3;
    mb.obj03.os_event_send = mb_os_send;
    mb.obj03.os_rtu_end_event = 1;
    mb.obj03.os_timeout_event = 2;
    
    mb_obj_init(&mb.obj02);

    //master config
    mb02_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_115200], MB_PAR_NONE);
    mb.obj02.slave_id = 2;
    mb.obj02.rtu_rcv_end_delay_set = 3;
    mb.obj02.rcv_end_handle_comp = rcv_end_handle_comp;
    mb.obj02.os_event_send = mb_os_send;
    mb.obj02.os_rtu_end_event = 1;
    mb.obj02.os_timeout_event = 2;
    
    //cmd config
    //mb.obj02.api->stc_cmd_req(0, 0, FUN_CODE_WRITE_MULTIPLE_REG, mb_tst.pv_w, 0, 48, 0);
    //mb.obj02.api->stc_cmd_req(1, 0, FUN_CODE_READ_REG, mb_tst.pv_r, 0, 48, 0);

    //task handle
    for(;;)
    {
        //wait modbus event
        os_err = tx_event_flags_get(os_obj.eid_mb, 
                           0xFFFF,
                           TX_OR_CLEAR, 
                           &event,
                           ms_ticks(3000));
        //os_api_exe_check();
        
        (void)os_err;
        
        ticks = bsp_cpu_clks_get() - sys_st.clks_at_event_rcv;
        
        if(ticks < 400)
            dbg_print("evevt ack time: %d\n",ticks);
        
        mb_poll(&mb.obj03);
        
        mb_poll(&mb.obj02);
    }
}

void rcv_end_handle_comp(uint8_t ErrSt)
{
    if(0 == ErrSt)
    {

    }
}

